package com.yonyou.ypd.bizflow.utils;


import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.isvrequest.ISVRequest;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.isvrequest.ISVRequestBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.poi.util.StringUtil;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * 通讯https工具类
 *
 * @author lizhgb
 * @date 2015-9-6l
 */
@Slf4j
public class HttpClientUtil {

    private static CloseableHttpClient httpclient = createSSLClientDefault();

    private static ISVRequest isvRequest = AppContext.getBean(ISVRequest.class);
    private static final String DEFAULT_CHARSET_UTF8 = "UTF-8";
    private static final String DEFAULT_CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
    private static final String DEFAULT_CONTENT_TYPE_JSON = "application/json";
    private static final int MAX_TIMEOUT = 55000;
    private static final int MAX_RETRY_TIMES = 5;
    private static final int MAX_THREAD_TOTAL = 50;


    public static List<NameValuePair> getParams(HttpServletRequest request) {

        List<NameValuePair> params = new ArrayList<>();
        Map<String, String[]> paramMap = request.getParameterMap();
        if (paramMap != null && !paramMap.isEmpty()) {
            Iterator<String> keys = paramMap.keySet().iterator();
            while (keys.hasNext()) {
                String key = keys.next();
                String[] values = paramMap.get(key);
                NameValuePair nameValuePair = new BasicNameValuePair(key, StringUtil.join(values));
                params.add(nameValuePair);
            }
        }
        return params;
    }


    /**
     * 发送https post请求
     *
     * @param action
     * @param bodyParam
     * @return
     * @throws Exception
     * @author lizhgb
     * @Date 2015-9-10 上午11:12:55
     */
    public static String httpsPost(String action, Object bodyParam) throws Exception {
        return httpsPost(action, null, bodyParam);
    }


    /**
     * 发送https post请求
     *
     * @param url
     * @param bodyParam
     * @return
     * @throws Exception
     */
    public static String httpsPostForm(String url, List<NameValuePair> bodyParam) throws Exception {
        return httpsPostForm(url, null, bodyParam);
    }


    /**
     * 发送https post请求
     *
     * @param url
     * @return
     * @throws Exception
     * @author lizhgb
     * @Date 2015-9-6 下午1:32:06
     */
    public static String httpsPostForm(String url, Map<String, String> headerParams, List<NameValuePair> bodyParams) throws Exception {


        log.info("Post请求地址：" + url);

        HttpPost httpPost = new HttpPost(url);

        //header参数
        httpPost.addHeader("Content-Type", DEFAULT_CONTENT_TYPE_FORM);
        if (headerParams != null && headerParams.size() > 0) {
            log.info("Post请求Header：" + JsonUtil.toJSONString(headerParams));
            for (String key : headerParams.keySet()) {
                httpPost.addHeader(key, headerParams.get(key));
            }
        }

        //entity数据
        if (bodyParams != null) {
            log.info("Post请求Body：" + JsonUtil.toJSONString(bodyParams));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(bodyParams, DEFAULT_CHARSET_UTF8);
            httpPost.setEntity(entity);
        }

        String resultStr = null;
        try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
            resultStr = EntityUtils.toString(response.getEntity(), "utf-8");
            int statusCode = response.getStatusLine().getStatusCode();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new Exception(getHttpInfoStr(statusCode, url, headerParams, bodyParams, resultStr));
            }
        } catch (IOException e) {
            throw new Exception(getHttpInfoStr(null, url, headerParams, bodyParams, resultStr));
        } finally {
            httpPost.releaseConnection();
        }

        log.info("Post请求返回：" + resultStr);
        return resultStr;
    }

    /**
     * 发送https post请求
     *
     * @param action
     * @return
     * @throws Exception
     * @author lizhgb
     * @Date 2015-9-6 下午1:32:06
     */
    public static String httpsPost(String action, Map<String, String> headerParams, Object bodyParams) throws Exception {


        String url = action;
        log.info("Post请求地址：" + url);

        HttpPost httpPost = new HttpPost(url);

        //header参数
        if (headerParams != null && headerParams.size() > 0) {
            log.info("Post请求Header：" + JsonUtil.toJSONString(headerParams));
            for (String key : headerParams.keySet()) {
                httpPost.addHeader(key, headerParams.get(key));
            }
        }

        //entity数据
        if (bodyParams != null) {
            log.info("Post请求Body：" + JsonUtil.toJSONString(bodyParams));
            StringEntity entity = new StringEntity(JsonUtil.toJSONString(bodyParams), DEFAULT_CHARSET_UTF8);
            entity.setContentEncoding(DEFAULT_CHARSET_UTF8);
            entity.setContentType(DEFAULT_CONTENT_TYPE_JSON);
            httpPost.setEntity(entity);
        }

        if (InvocationInfoProxy.getYhtAccessToken()!=null && !InvocationInfoProxy.getYhtAccessToken().startsWith("btt")) {
            ISVRequestBody isvRequestBody = new ISVRequestBody();
            isvRequestBody.setUrl(url);
            isvRequestBody.setRequestMethod("POSTJSON");
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("data", JSONObject.toJSONString(bodyParams));
            isvRequestBody.setParams(hashMap);
            String yhtAccessToken = InvocationInfoProxy.getYhtAccessToken();
            if(headerParams == null) {
                headerParams = new HashMap<>();
            }
            headerParams.put("yht_access_token", yhtAccessToken);
            isvRequestBody.setHeaders(headerParams);
            String result = isvRequest.doRequest(InvocationInfoProxy.getTenantid(), isvRequestBody);
            return result;
        }

        String resultStr = null;
        try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
            resultStr = EntityUtils.toString(response.getEntity(), "utf-8");
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                throw new Exception(getHttpInfoStr(statusCode, url, headerParams, bodyParams, resultStr));
            }
        } catch (IOException e) {
            throw new Exception(getHttpInfoStr(null, url, headerParams, bodyParams, resultStr), e);
        } finally {
            httpPost.releaseConnection();
        }


        log.info("Post请求返回：" + resultStr);
        return resultStr;
    }


    public static String getHttpInfoStr(Integer statusCode, String url, Map<String, String> headerParam, Object bodyParams, String resultStr) {
        return "【Post请求异常】" + "status:" + statusCode + ", url:" + url + ", header:" + JsonUtil.toJSONString(headerParam) + ", body:" + JsonUtil.toJSONString(bodyParams) + ", result:" + resultStr;
    }

    public static String getHttpInfoStr(String url, Map<String, String> headerParams, Object bodyParams, String resultStr) {
        return getHttpInfoStr(null, url, headerParams, bodyParams, resultStr);
    }

    /**
     * 发送https get请求
     *
     * @param url
     * @return
     * @throws Exception
     * @author lizhgb
     * @Date 2015-9-7 上午9:06:57
     */
    public static String httpsGet(String url, Map<String, String> headerParams, List<NameValuePair> bodyParams) throws Exception {

        URIBuilder uriBuilder = new URIBuilder();
        if (bodyParams != null && !bodyParams.isEmpty()) {
            for (NameValuePair pair : bodyParams) {
                uriBuilder.setParameter(pair.getName(), pair.getValue());
            }
        }
        String urlWithParam = url + uriBuilder.toString();

        log.info("Get请求地址：" + urlWithParam);
        HttpGet httpGet = new HttpGet(urlWithParam);

        httpGet.addHeader("Content-Type", DEFAULT_CONTENT_TYPE_FORM);
        if (headerParams != null && !headerParams.isEmpty()) {
            for (Map.Entry<String, String> entry : headerParams.entrySet()) {
                httpGet.addHeader(entry.getKey(), entry.getValue());
            }
        }

        if (InvocationInfoProxy.getYhtAccessToken()!=null && !InvocationInfoProxy.getYhtAccessToken().startsWith("btt")) {
            ISVRequestBody isvRequestBody = new ISVRequestBody();
            isvRequestBody.setUrl(urlWithParam);
            isvRequestBody.setRequestMethod("GET");
            HashMap<String, String> paramsMap = new HashMap<>();
            isvRequestBody.setParams(null);
            String yhtAccessToken = InvocationInfoProxy.getYhtAccessToken();
            if(headerParams == null) {
                headerParams = new HashMap<>();
            }
            headerParams.put("yht_access_token", yhtAccessToken);
            isvRequestBody.setHeaders(headerParams);
            String result = isvRequest.doRequest(InvocationInfoProxy.getTenantid(), isvRequestBody);
            return result;
        }

        String resultStr = null;
        try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
            resultStr = EntityUtils.toString(response.getEntity(), DEFAULT_CHARSET_UTF8);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                throw new Exception(getHttpInfoStr(statusCode, url, headerParams, bodyParams, resultStr));
            }
        } catch (IOException e) {
            throw new Exception(getHttpInfoStr(null, url, headerParams, bodyParams, resultStr), e);
        } finally {
            httpGet.releaseConnection();
        }

        log.info("Get请求返回：" + resultStr);
        return resultStr;
    }


    /**
     * 发送https get请求
     *
     * @param url
     * @return
     * @throws Exception
     * @author lizhgb
     * @Date 2015-9-7 上午9:06:57
     */
    public static String httpsGet(String url) throws Exception {
        return httpsGet(url, null, null);
    }


    /**
     * 发送https get请求
     *
     * @param url
     * @return
     * @throws Exception
     * @author lizhgb
     * @Date 2015-9-7 上午9:06:57
     */
    public static String httpsGet(String url, List<NameValuePair> bodyParams) throws Exception {
        return httpsGet(url, null, bodyParams);
    }


    /**
     * 创建httpclient
     *
     * @return
     */
    private static synchronized CloseableHttpClient createSSLClientDefault() {

        SSLContext sslContext = null;
        try {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
        } catch (Exception e) {
            log.error("http client init error! " + e.getMessage());
        }

        assert sslContext != null;
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
        ConnectionSocketFactory psf = PlainConnectionSocketFactory.getSocketFactory();

        Registry<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", csf)
                .register("http", psf)
                .build();

        RequestConfig config = RequestConfig.custom()
                .setSocketTimeout(MAX_TIMEOUT)
                .setConnectTimeout(MAX_TIMEOUT)
                .setConnectionRequestTimeout(MAX_TIMEOUT)
                .build();

        //超时重试处理
        HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(MAX_RETRY_TIMES, true);

        //连接管理池
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registryBuilder);
        cm.setMaxTotal(MAX_THREAD_TOTAL);
        cm.setDefaultMaxPerRoute(MAX_THREAD_TOTAL);

        return HttpClients.custom().setConnectionManager(cm).setSSLSocketFactory(csf).setDefaultRequestConfig(config).setRetryHandler(retryHandler).build();
    }
}
